package com.example.fresheveryday.Realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.fresheveryday.po.Role;
import com.example.fresheveryday.po.RolePermission;
import com.example.fresheveryday.po.User;
import com.example.fresheveryday.po.UserRole;
import com.example.fresheveryday.service.*;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RolePermissionService rolePermissionService;
    @Override
    public String getName() {
        return "myRealm";
    }

    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.iterator().next();
        //根据当前用户查询role
        Set<String> rolenames = roleService.queryRoleNameByUserId(String.valueOf(user.getId()));
        Set<String> permissions = permissionService.queryPermissionByUserId(String.valueOf(user.getId()));
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(rolenames);
        simpleAuthorizationInfo.setStringPermissions(permissions);

        return simpleAuthorizationInfo;
    }

    @Override//验证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
        String username = usernamePasswordToken.getUsername();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("email",username);
        User user = userService.getOne(wrapper);
        if(user == null){
            return  null;
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
